package cn.matezk.cloud.framework;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.matezk.cloud.beans.Result;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.util.NestedServletException;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public ResponseEntity<Result> handlerException(Exception e) {
        log.error("全局异常捕获", e);
        if (e instanceof HttpRequestMethodNotSupportedException) {
            return ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE).body(new Result(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(), e.getMessage(), null));
        } else if (e instanceof NestedServletException) {
            String msg = e.getMessage();
            if (ObjectUtil.isNotEmpty(msg) && msg.indexOf("java.lang.InternalError: ") >= 0)
                msg = msg.substring(msg.indexOf("java.lang.InternalError: ") + "java.lang.InternalError: ".length());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.error(msg));
        } else if (e instanceof TencentCloudSDKException) {
            TencentCloudSDKException exception = (TencentCloudSDKException)e;
            Result error = new Result();
            error.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            error.setMsg(exception.getMessage());
            error.setData(JSONUtil.createObj().set("RequestId", exception.getRequestId()).set("Message", exception.getMessage()).set("Code", exception.getErrorCode()));
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.error(e.getMessage()));
    }
}
